package com.example.mydy;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.cardview.widget.CardView;

import com.example.mydy.model.UserInfo;
import com.example.mydy.utils.AchievementManager;
import com.example.mydy.utils.ActivityManager;
import com.example.mydy.utils.MockDataManager;
import com.example.mydy.utils.NetworkUtils;

public class UserProfileActivity extends AppCompatActivity {

    private static final String TAG = "UserProfileActivity";
    private static final String PREFS_NAME = "MyAppPrefs";
    private static final String KEY_IS_LOGGED_IN = "isLoggedIn";

    private MockDataManager mockDataManager;
    private ActivityManager activityManager;
    private AchievementManager achievementManager;
    private UserInfo currentUser;

    // UI元素
    private ImageView userAvatar;
    private TextView userName;
    private TextView userLevel;
    private TextView userBalance;
    private TextView userPoints;
    private TextView inviteCode;
    private CardView achievementsCard;
    private CardView tasksCard;
    private CardView withdrawalCard;
    private CardView settingsCard;
    private Button logoutButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_profile);

        // 初始化工具类
        mockDataManager = MockDataManager.getInstance();
        activityManager = ActivityManager.getInstance(this);
        achievementManager = AchievementManager.getInstance(this);

        // 获取当前用户
        currentUser = mockDataManager.getCurrentUser();
        if (currentUser == null) {
            Toast.makeText(this, "用户未登录，请先登录", Toast.LENGTH_SHORT).show();
            navigateToLogin();
            return;
        }

        initViews();
        loadUserData();
        setupClickListeners();
    }

    private void initViews() {
        // 初始化头像和基本信息
        userAvatar = findViewById(R.id.user_avatar);
        userName = findViewById(R.id.user_name);
        userLevel = findViewById(R.id.user_level);
        userBalance = findViewById(R.id.user_balance);
        userPoints = findViewById(R.id.user_points);
        inviteCode = findViewById(R.id.invite_code);

        // 初始化功能卡片
        achievementsCard = findViewById(R.id.achievements_card);
        tasksCard = findViewById(R.id.tasks_card);
        withdrawalCard = findViewById(R.id.withdrawal_card);
        settingsCard = findViewById(R.id.settings_card);
        
        // 初始化退出登录按钮
        logoutButton = findViewById(R.id.logout_button);
    }

    private void loadUserData() {
        if (currentUser != null) {
            // 设置用户名和昵称
            userName.setText(currentUser.getNickname() != null ? 
                    currentUser.getNickname() : currentUser.getUsername());
            
            // 设置用户等级
            userLevel.setText(activityManager.getUserActivityLevelName(currentUser.getUsername()));
            
            // 设置用户余额
            userBalance.setText(String.format("¥ %.2f", Double.parseDouble(currentUser.getBalance())));
            
            // 设置用户积分
            userPoints.setText(String.valueOf(currentUser.getPoints()));
            
            // 设置邀请码
            inviteCode.setText(currentUser.getInviteCode() != null ? 
                    currentUser.getInviteCode() : "未设置");
                    
            // 设置头像 (在实际应用中应该加载用户头像)
            // userAvatar.setImageResource(R.drawable.default_avatar);
        }
    }

    private void setupClickListeners() {
        // 设置成就卡片点击事件
        achievementsCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserProfileActivity.this, AchievementsActivity.class);
                startActivity(intent);
            }
        });

        // 设置任务卡片点击事件
        tasksCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserProfileActivity.this, TaskManagementActivity.class);
                startActivity(intent);
            }
        });

        // 设置提现卡片点击事件
        withdrawalCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(UserProfileActivity.this, WithdrawalActivity.class);
                startActivity(intent);
            }
        });

        // 设置设置卡片点击事件
        settingsCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(UserProfileActivity.this, "设置功能开发中...", Toast.LENGTH_SHORT).show();
            }
        });

        // 设置退出登录按钮点击事件
        logoutButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showLogoutConfirmDialog();
            }
        });
    }

    private void showLogoutConfirmDialog() {
        new AlertDialog.Builder(this)
                .setTitle("退出登录")
                .setMessage("确定要退出登录吗？")
                .setPositiveButton("确定", (dialog, which) -> {
                    performLogout();
                })
                .setNegativeButton("取消", null)
                .show();
    }

    private void performLogout() {
        // 清除登录状态
        SharedPreferences prefs = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
        prefs.edit().putBoolean(KEY_IS_LOGGED_IN, false).apply();
        
        // 调用NetworkUtils的登出方法
        NetworkUtils.mockLogout();
        
        Toast.makeText(this, "已退出登录", Toast.LENGTH_SHORT).show();
        
        // 返回登录页面
        navigateToLogin();
    }

    private void navigateToLogin() {
        Intent intent = new Intent(this, LoginActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
        finish();
    }
} 